<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/10/9
 * Time: 下午1:51
 */
class WxwOrderController extends BaseController {
    /*
     * test
     * */
    public function test(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            $result = array();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);

        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "test", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 订单详情
     * */
    public function show(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id'  => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            $order = Orders::where('user_id',$user_data->id)
                ->where('order_id',$order_id)
                ->select(array('order_id','status','name','tittle','phone','book_time','place','shop_id','address','note','amount'))
                ->get()->toArray();
//            $prodects = OrderProduct::join('product_package','product_package.id','=','order_product.product_id')
//                ->where('order_product.order_id',$order_id)
//                ->where('order_product.status',1)
//                ->select(array('order_product.product_id','product_package.name','order_product.num','order_product.amount'))
//                ->orderBy("order_product.created_at", "desc")
//                ->get()->toArray();
            $prodects = OrderProduct::getOrderProduct($order_id);
            $order[0]['products'] = $prodects;
            $result = array(
                'order' => $order
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);

        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 订单列表
     * */
    public function history(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $limit = Input::get("limit", 10);
            $offset = Input::get("offset", 0);

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            $orders = Orders::where('user_id',$user_data->id)
                ->skip($offset)
                ->take($limit)
                ->select(array('order_id','status','name','tittle','phone','book_time','place','shop_id','address'))
                ->orderBy("created_at", "desc")
                ->get()->toArray();

            $count = count($orders);
            $result = array(
                'count' => $count,
                'orders' => $orders
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);

        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "test", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 订单取消
     * 客服派单之后才会占用库存，因此用户取消不影响库存量
     * */
    public function cancel(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            try {
                //更新订单表
                Orders::where('order_id',$order_id)->update(array('status' => Config::get('order.custom_cancel_order_status')));

                //订单流转表新增记录
                $order_flows = new OrderFlows;
                $order_flows->order_id = $order_id;
                $order_flows->status = Config::get('order.custom_cancel_order_status');
                $order_flows->user_id = $user_data->id;
                $order_flows->type = 'custom';
                $order_flows->created_at = Common::num2DateTime(time());
                $order_flows->save();

                //更新订单产品表
                OrderProduct::where('order_id',$order_id)->update(array('status' => 0));
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "cancel", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.order_cancel_error_1020");
                break;
            }
            $result = array(
                'order_id' => $order_id,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);

        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "cancel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 下单
     * */
    public function create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'place' => 'required',
                'book_time' => 'required',
                'name' => 'required',
                'tittle' => 'required',
                'phone' => 'required',
                'pay_type' => 'required',
                'user_car_id' => 'required',
                'products' => 'required',
                'amount' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $city = Input::get('city')?Input::get('city'):1; //订单城市
            $place = Input::get('place'); //1-上门订单，2-到店订单
            $book_time = Input::get('book_time'); //预约时间
            $shop_id = Input::get('shop_id'); //预约门店ID
            $address = Input::get('address'); //预约上门地址
            $name = Input::get('name'); //联系人
            $tittle = Input::get('tittle'); //称呼，先生 or 女士
            $phone = Input::get('phone'); //联系电话
            $pay_type = Input::get('pay_type'); //支付方式
            $user_car_id = Input::get('user_car_id'); //用户车辆ID
            $note = Input::get('note'); //订单备注
            $products = Input::get('products'); //产品list array(产品ID，数量，金额)
            $amount = Input::get('amount'); //订单金额

            $order_id = Common::createOrderId();
            // todo 需要和李国峰确认页面传入的list array 约定格式。

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }
            try {
                $order = new Orders;
                $order->order_id = $order_id;
                $order->user_id = $user_data->id;
                $order->city = $city;
                $order->place = $place;
                $order->book_time = $book_time;
                $order->shop_id = $shop_id;
                $order->address = $address;
                $order->name = $name;
                $order->tittle = $tittle;
                $order->phone = $phone;
                $order->pay_type = $pay_type;
                $order->user_car_id = $user_car_id;
                $order->amount = $amount;
                $order->status = Config::get('order.custom_create_order_status');
                $order->note = $note;
                $order->created_at = Common::num2DateTime(time());
                $order->save();

                $order_flows = new OrderFlows;
                $order_flows->order_id = $order_id;
                $order_flows->status = Config::get('order.custom_create_order_status');;
                $order_flows->user_id = $user_data->id;
                $order_flows->type = 'custom';
                $order_flows->created_at = Common::num2DateTime(time());
                $order_flows->save();

                // todo product list 处理 array2json ｜ json_decode
                $order_product = new OrderProduct;
                $products=json_decode($products);
                $datas = array();
                foreach($products as $product){
                    $data = array(
                        'order_id' => $order_id,
                        'product_id' => $product->id,
                        'num' => $product->num,
                        'amount' => $product->amount,
                        'status' => 1,
                        'created_at' => Common::num2DateTime(time())
                    );
                    array_push($datas,$data);
                }
                $order_product->insert($datas);
            } catch (Exception $e) {
                Log::error("error", array("system" => "wxw" ,"event" => "create", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.order_create_error_1019");
                break;
            }
            $result = array(
                'order_id' => $order_id,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);

        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 获取上门车可用时间信息
     * */
    public function car(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $city = Input::get('city')?Input::get('city'):1;
            $date_start = Input::get('date')?Input::get('date'):Common::num2DateTime(time(),'Y-m-d');
            $date_stop = Common::num2DateTime(Common::datetime2Num($date_start) + Config::get("order.car_reserve_day"),'Y-m-d');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }

            //获取上门车可用时间
            $cars = CarStockOrder::where('city',$city)
                ->whereBetween('stock_date',array($date_start,$date_stop))
                ->whereRaw('stock_all > stock_current')
                ->select(array('stock_date','stock_all','stock_current'))
                ->orderBy('stock_date', 'asc')
                ->get()->toArray();
            $days = array();
            foreach($cars as $car){
                $day = array(
                    'date' => $car['stock_date'],
                    'cars' => $car['stock_all'] - $car['stock_current'],
                );
                array_push($days,$day);
            }
            $count = count($days);
            $result = array(
                'count' => $count,
                'days' => $days
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);

        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "car", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 获取可用门店信息
     * */
    public function shop(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.user_login_args_error_1011");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $city = Input::get('city')?Input::get('city'):1;
            $date = Input::get('date')?Input::get('date'):Common::num2DateTime(time(),'Y-m-d');

            //验证token
            $user_data = Users::getUserByToken($token);
            if(is_numeric($user_data) && $user_data < 0){
                $response = Lang::get("error.user_token_not_exist_1004");
                break;
            }
            //todo 获取用户坐标，根据geohash找到最近的门店。
            //获取门店信息
            $shops = MaintenanceShops::join('shop_stock_order','maintenance_shops.id', '=', 'shop_stock_order.shop_id')
                ->where('shop_stock_order.stock_date',$date)
                ->whereRaw('shop_stock_order.stock_all > shop_stock_order.stock_current')
                ->where('maintenance_shops.status',1)
                ->where('maintenance_shops.city',$city)
                ->select(array('maintenance_shops.id','maintenance_shops.name','maintenance_shops.desc','maintenance_shops.address'))
                ->orderBy('maintenance_shops.stock', 'desc')
                ->get()->toArray();
//            $queries = DB::getQueryLog();
//            var_dump($queries);
            $count = count($shops);
            $result = array(
                'count' => $count,
                'shops' => $shops
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);

        } while (false);
        Log::info("info", array("system" => "wxw" ,"event" => "shop", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}